<template>
  <div class="exam-edit-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑考试' : '创建考试' }}</span>
        </div>
      </template>

      <el-form
        ref="examForm"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="考试名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>

        <el-form-item label="考试时间" prop="examTime">
          <el-date-picker
            v-model="form.examTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>

        <el-form-item label="考试时长" prop="duration">
          <el-input-number
            v-model="form.duration"
            :min="30"
            :max="180"
            :step="30"
          />
          <span class="unit">分钟</span>
        </el-form-item>

        <el-form-item label="总分" prop="totalScore">
          <el-input-number
            v-model="form.totalScore"
            :min="0"
            :max="100"
          />
          <span class="unit">分</span>
        </el-form-item>

        <el-divider>试题管理</el-divider>

        <!-- 试题列表 -->
        <div class="question-list">
          <div
            v-for="(question, index) in form.questions"
            :key="index"
            class="question-item"
          >
            <div class="question-header">
              <span>第{{ index + 1 }}题（{{ question.score }}分）</span>
              <div class="question-actions">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeQuestion(index)"
                >
                  删除
                </el-button>
              </div>
            </div>
            <div class="question-content">
              <p>{{ question.title }}</p>
              <p class="question-type">类型：{{ questionTypeMap[question.type] }}</p>
            </div>
          </div>
        </div>

        <!-- 添加试题 -->
        <el-button
          type="primary"
          @click="showQuestionSelector"
          class="add-question-btn"
        >
          添��试题
        </el-button>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 试题选择对话框 -->
    <el-dialog
      v-model="questionSelectorVisible"
      title="选择试题"
      width="70%"
    >
      <el-form :inline="true" class="search-form">
        <el-form-item label="试题类型">
          <el-select v-model="questionSearchForm.type">
            <el-option label="全部" value="" />
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="填空题" value="blank" />
            <el-option label="编程题" value="programming" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="questionSearchForm.difficulty">
            <el-option label="全部" value="" />
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchQuestions">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="questionBank"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="题目" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            {{ questionTypeMap[scope.row.type] }}
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="100">
          <template #default="scope">
            {{ difficultyMap[scope.row.difficulty] }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分值" width="80" />
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="questionSelectorVisible = false">取消</el-button>
          <el-button type="primary" @click="addSelectedQuestions">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const isEdit = computed(() => route.params.id)

const questionTypeMap = {
  single: '单选题',
  multiple: '多选题',
  blank: '填空题',
  programming: '编程题'
}

const difficultyMap = {
  easy: '简单',
  medium: '中等',
  hard: '困难'
}

// 表单数据
const form = reactive({
  name: '',
  examTime: [],
  duration: 120,
  totalScore: 100,
  questions: []
})

const rules = {
  name: [
    { required: true, message: '请输入考试名称', trigger: 'blur' }
  ],
  examTime: [
    { required: true, message: '请选择考试时间', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请设置考试时长', trigger: 'change' }
  ],
  totalScore: [
    { required: true, message: '请设置总分', trigger: 'change' }
  ]
}

// 试题选择
const questionSelectorVisible = ref(false)
const questionSearchForm = reactive({
  type: '',
  difficulty: ''
})
const selectedQuestions = ref([])

// 模拟题库数据
const questionBank = ref([
  {
    id: 1,
    title: '以下哪个不是C语言的基本数据类型？',
    type: 'single',
    difficulty: 'easy',
    score: 2
  },
  {
    id: 2,
    title: '关于指针的说法，以下正确的是：',
    type: 'multiple',
    difficulty: 'medium',
    score: 4
  }
])

const showQuestionSelector = () => {
  questionSelectorVisible.value = true
}

const searchQuestions = () => {
  // 实现试题搜索逻辑
}

const handleSelectionChange = (selection) => {
  selectedQuestions.value = selection
}

const addSelectedQuestions = () => {
  form.questions.push(...selectedQuestions.value)
  questionSelectorVisible.value = false
  selectedQuestions.value = []
}

const removeQuestion = (index) => {
  form.questions.splice(index, 1)
}

const handleSubmit = async () => {
  try {
    // 实现提交逻辑
    ElMessage.success(isEdit.value ? '保存成功' : '创建成功')
    router.push('/teacher/exams')
  } catch (error) {
    ElMessage.error('操作失败：' + error.message)
  }
}
</script>

<style scoped>
.exam-edit-container {
  padding: 20px;
}

.unit {
  margin-left: 10px;
  color: #606266;
}

.question-list {
  margin: 20px 0;
}

.question-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-bottom: 10px;
  padding: 15px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.question-content {
  color: #606266;
}

.question-type {
  color: #909399;
  font-size: 14px;
  margin-top: 5px;
}

.add-question-btn {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}
</style> 